package filters;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class SessionFilter
 */

//本程序过滤不经过登录页面而直接到其他页面，另外会话过期也会回到登录

//@WebFilter("/SessionFilter")
public class SessionFilter implements Filter  {
       
    /**
     * @see Filter#Filter()
     */
    public SessionFilter() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		//chain.doFilter(request, response);
		 HttpSession sess = ((HttpServletRequest)request).getSession();
	     String userno = (String)sess.getAttribute("userno");
	     if(userno==null ){
	    	   	//方法1，适合于不使用iframe的时候，直接跳转
	    	 	//((HttpServletResponse)response).sendRedirect(((HttpServletRequest)request).getContextPath()+"/login.jsp");
	    	 	
	    	 	//方法2，适合于跳转的时候，在一个新的页面，而不是将登录页面放到iframe中
	    	 	PrintWriter out = response.getWriter();
			    out.println("<html>");    
			    out.println("<script>");    
			   // out.println("window.open ('"+request.getServletContext().getRealPath("")+"/login.jsp','_top')"); 
			    out.println("window.open ('login.jsp','_top')");  //request.getContextPath()
			    out.println("</script>");    
			    out.println("</html>");  
				

	     }else{
	            chain.doFilter(request, response);
	     }
	
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		fConfig.getInitParameter("param-name");
	}

}
